"use client";

import { useEffect, useState } from "react";
import axios from "axios";
import { formatCurrency, formatLargeNumber, getPriceChangeClass } from "@/lib/utils";
import { useWallet } from "@/context/WalletContext";
import { FiTrendingUp, FiTrendingDown, FiDollarSign } from "react-icons/fi";

interface CryptoData {
  id: string;
  name: string;
  symbol: string;
  image: string;
  current_price: number;
  market_cap: number;
  price_change_percentage_24h: number;
}

export default function Home() {
  const [cryptos, setCryptos] = useState<CryptoData[]>([]);
  const [loading, setLoading] = useState<boolean>(true);
  const [error, setError] = useState<string | null>(null);
  const { address, balance } = useWallet();

  useEffect(() => {
    const fetchCryptoData = async () => {
      setLoading(true);
      setError(null);

      try {
        const response = await axios.get(
          "https://api.coingecko.com/api/v3/coins/markets",
          {
            params: {
              vs_currency: "usd",
              order: "market_cap_desc",
              per_page: 10,
              page: 1,
              sparkline: false,
              locale: "en",
            },
          }
        );

        setCryptos(response.data);
      } catch (err) {
        setError("Failed to load crypto market data. Please try again later.");
        console.error("Fetch crypto error:", err);
      } finally {
        setLoading(false);
      }
    };

    fetchCryptoData();
  }, []);

  const calculateTotalAssets = () => {
    if (!balance || !cryptos.length) return 0;
    const ethData = cryptos.find((crypto) => crypto.symbol === "eth");
    return ethData ? parseFloat(balance) * ethData.current_price : 0;
  };

  return (
    <div className="space-y-8">
      {/* 页面标题 + 用户资产卡片 */}
      <div className="flex flex-col md:flex-row justify-between items-start md:items-center gap-6">
        <div>
          <h1 className="text-3xl font-bold tracking-tight">Crypto Market</h1>
          <p className="text-gray-600 dark:text-gray-400 mt-1 max-w-2xl">
            Track top cryptocurrencies and monitor your portfolio value in real-time
          </p>
        </div>

        {address && (
          <div className="w-full md:w-auto p-4 bg-white dark:bg-gray-800 rounded-lg shadow-sm border dark:border-gray-700 w-full max-w-xs">
            <div className="flex items-center gap-3">
              <div className="p-2 bg-indigo-100 dark:bg-indigo-900/30 rounded-md">
                <FiDollarSign className="h-5 w-5 text-indigo-600 dark:text-indigo-400" />
              </div>
              <div>
                <p className="text-sm text-gray-500 dark:text-gray-400">Your Total Assets</p>
                <p className="text-xl font-bold">{formatCurrency(calculateTotalAssets())}</p>
                <p className="text-xs text-gray-500 dark:text-gray-400">
                  {balance ? `${parseFloat(balance).toFixed(4)} ETH` : "Loading..."}
                </p>
              </div>
            </div>
          </div>
        )}
      </div>

      {/* 错误提示 */}
      {error && (
        <div className="p-4 bg-red-50 dark:bg-red-900/20 border border-red-200 dark:border-red-800 text-red-700 dark:text-red-300 rounded-lg flex items-start gap-3">
          <svg xmlns="http://www.w3.org/2000/svg" className="h-5 w-5 mt-0.5 flex-shrink-0" viewBox="0 0 20 20" fill="currentColor">
            <path fillRule="evenodd" d="M18 10a8 8 0 11-16 0 8 8 0 0116 0zm-7 4a1 1 0 11-2 0 1 1 0 012 0zm-1-9a1 1 0 00-1 1v4a1 1 0 102 0V6a1 1 0 00-1-1z" clipRule="evenodd" />
          </svg>
          <p>{error}</p>
        </div>
      )}

      {/* 加载中：骨架屏 */}
      {loading && !error ? (
        <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-6">
          {Array.from({ length: 8 }).map((_, i) => (
            <div key={i} className="p-6 bg-white dark:bg-gray-800 rounded-lg shadow-sm border dark:border-gray-700 animate-pulse">
              <div className="flex items-center mb-4">
                <div className="h-10 w-10 rounded-full bg-gray-200 dark:bg-gray-700 mr-3"></div>
                <div className="space-y-2">
                  <div className="h-4 bg-gray-200 dark:bg-gray-700 rounded w-24"></div>
                  <div className="h-3 bg-gray-200 dark:bg-gray-700 rounded w-16"></div>
                </div>
              </div>
              <div className="space-y-2 mb-4">
                <div className="h-3 bg-gray-200 dark:bg-gray-700 rounded w-20"></div>
                <div className="h-6 bg-gray-200 dark:bg-gray-700 rounded w-32"></div>
              </div>
              <div className="flex justify-between">
                <div className="space-y-2">
                  <div className="h-3 bg-gray-200 dark:bg-gray-700 rounded w-20"></div>
                  <div className="h-4 bg-gray-200 dark:bg-gray-700 rounded w-24"></div>
                </div>
                <div className="h-4 bg-gray-200 dark:bg-gray-700 rounded w-20"></div>
              </div>
            </div>
          ))}
        </div>
      ) : (
        // 数据展示：加密货币卡片列表
        <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-6">
          {cryptos.map((crypto) => (
            <div
              key={crypto.id}
              className="p-6 bg-white dark:bg-gray-800 rounded-lg shadow-sm border dark:border-gray-700 hover:shadow-md transition-all duration-300 hover:-translate-y-1"
            >
              {/* 币种图标+名称 */}
              <div className="flex items-center mb-4">
                <img
                  src={crypto.image}
                  alt={`${crypto.name} logo`}
                  className="h-10 w-10 rounded-full mr-3 object-cover border border-gray-100 dark:border-gray-700"
                />
                <div>
                  <h3 className="font-bold text-lg">{crypto.name}</h3>
                  <p className="text-sm text-gray-500 dark:text-gray-400 uppercase">{crypto.symbol}</p>
                </div>
              </div>

              {/* 当前价格 */}
              <div className="mb-4">
                <p className="text-sm text-gray-500 dark:text-gray-400">Current Price</p>
                <p className="text-2xl font-bold">{formatCurrency(crypto.current_price)}</p>
              </div>

              {/* 市值 + 24h涨跌 */}
              <div className="flex justify-between items-end">
                <div>
                  <p className="text-sm text-gray-500 dark:text-gray-400">Market Cap</p>
                  <p className="font-medium">{formatLargeNumber(crypto.market_cap)}</p>
                </div>
                <div className={`flex items-center font-medium ${getPriceChangeClass(crypto.price_change_percentage_24h)}`}>
                  {crypto.price_change_percentage_24h >= 0 ? (
                    <FiTrendingUp className="h-4 w-4 mr-1" />
                  ) : (
                    <FiTrendingDown className="h-4 w-4 mr-1" />
                  )}
                  {crypto.price_change_percentage_24h.toFixed(2)}%
                </div>
              </div>
            </div>
          ))}
        </div>
      )}
    </div>
  );
}
